export default UglyPolygon

import {c, mouse} from "./canvas";

// n为边数
// x y为中心坐标
// a为中心到顶点的距离
// ang为逆时针旋转角度， 默认为0
function UglyPolygon(n, x, y, a, ang = 0, color = 'white') {
    this.n = n;
    this.x = x;
    this.y = y;
    this.a = a;
    this.ang = ang - Math.PI * 0.5;
    this.color = color;
    this.points = [];

    this.setPoints = function () {
        this.points = [];
        let tempAng = this.ang;
        console.log(this.n);
        const rotateAng = 2 * Math.PI / (this.n + 1);
        let tmpArray = [];
        tmpArray[0] = x + this.a * Math.cos(tempAng);
        tmpArray[1] = y + this.a * Math.sin(tempAng);
        this.points[0] = tmpArray;
        for (let i = 1; i < this.n; ++i) {
            let getSign;
            if (Math.random() <= 0.5) {
                getSign = 1;
            } else {
                getSign = -1;
            }
            let getRandomAngle = Math.ceil(Math.random() * 100000) % this.n * rotateAng;
            tempAng = tempAng - rotateAng + getSign * getRandomAngle;
            let tmpArray = [];
            tmpArray[0] = x + this.a * Math.cos(tempAng);
            tmpArray[1] = y + this.a * Math.sin(tempAng);
            this.points[i] = tmpArray;
        }
        console.log(this.points);

    }
    this.setPoints();

    this.show = function () {
        c.beginPath();
        c.moveTo(this.points[0][0], this.points[0][1]);
        console.log(this.points[0][0]);
        for (let i = 1; i < this.n; ++i) {
            c.lineTo(this.points[i][0], this.points[i][1]);
        }
        c.lineTo(this.points[0][0], this.points[0][1]);
        c.closePath();
        c.fillStyle = this.color;
        c.fill();
        c.stroke();
    }

    // 一个静态的多边形
    this.update = function () {
        this.show();
    }

    // 一个跟随鼠标转动的多边形
    this.updateWithMouse = function () {
        if (mouse.x === this.x) this.ang = -Math.PI * 0.5;
        else this.ang = Math.atan((mouse.y - this.y) / (mouse.x - this.x));

        this.show();
    }

    // 一个随机转动的多边形
    this.updateWithRandomAngle = function () {
        this.ang = this.ang + Math.random() % 2 * Math.PI;

        this.show();
    }

    this.changeAngle = function (ang) {
        this.ang = ang - Math.PI * 0.5;

    }

    this.changePosition = function (x, y) {
        this.x = x;
        this.y = y;
    }
}
